package com.sdx.console.contract.service;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ibeetl.admin.core.entity.BaseEntity;
import com.ibeetl.admin.core.entity.CoreUser;
import com.ibeetl.admin.core.web.AuthorizedBaesController;
import com.ibeetl.admin.core.web.JsonResult;
import com.sdx.console.contract.entity.ContractServiceRecord;
import com.sdx.console.utils.EDateUtil;
import com.sdx.service.ConfigService;
import org.beetl.sql.core.SQLManager;
import org.beetl.sql.core.SQLReady;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;

@Service
public class CreateContractService  extends AuthorizedBaesController {

    @Resource
    private SQLManager sqlManager;

//    private static final String uploadpath="C:/Users/Administrator/Desktop/uploadfile/";
//        private static final String uploadpath="https://sdxedu.oss-cn-beijing.aliyuncs.com/contract/";


    //上传文件。
    public  JSONObject upload(MultipartFile file, HttpServletRequest request){
        String uploadpath= ConfigService.contractuploadfile;

        JSONObject requestObj = null;
        //获取请求头
        String headerNames = request.getHeader("Content-Type");
        if (headerNames.contains("application/x-www-form-urlencoded")){
            StringBuilder sb= new StringBuilder();
            Map<String, String[]> parameterMap = request.getParameterMap();
            for (Map.Entry<String,String[]> entry : parameterMap.entrySet()){
                for (int i=0;i<entry.getValue().length;i++){
                    sb.append(entry.getKey());
                }
            }
            requestObj = JSONObject.parseObject(sb.toString());
        }
        if (headerNames.contains("multipart/form-data")){
            StringBuilder sb= new StringBuilder();
            Map<String,String[]> map =  request.getParameterMap();
            for (Map.Entry<String,String[]> entry : map.entrySet()){
                for (int i=0;i<entry.getValue().length;i++){
                    sb.append(entry.getValue()[i]);
                }
            }
            requestObj = JSONObject.parseObject(sb.toString());
        }

        String context = requestObj.getString("text");//内容
        String contractid = requestObj.getString("contractid");//id
        String srviceid = requestObj.getString("srviceid");//服务id
        String nodeid = requestObj.getString("nodeid");//流程id
        String invoiceno = requestObj.getString("invoiceno");//合同号
        String isuploadfile = requestObj.getString("isuploadfile");//是否上传文件
        String uploadFilePath=null;//上传文件路径

        JSONObject object = new JSONObject();
        String OriginalFilename =null;
        try {
            //判断是否上传文件
            File savafile = null;
            if (Boolean.valueOf(isuploadfile)){
                InputStream inputstream = file.getInputStream();//文件内容
                OriginalFilename = file.getOriginalFilename();//方法是得到原来的文件名在客户机的文件系统名称
                String fileName = file.getName(); //getName() 方法   返回参数的名称  这里返回的也就是  file
                uploadFilePath=uploadpath+"/"+invoiceno+"/"+srviceid+"/"+OriginalFilename;
                savafile = new File(uploadFilePath);
                System.out.println(savafile.getPath());
                System.out.println(savafile.getAbsolutePath());
                System.out.println(savafile.getCanonicalPath());
                System.out.println(savafile.getParentFile());
                System.out.println(savafile.getCanonicalPath());
                if (!savafile.getParentFile().exists()){
                    savafile.getParentFile().mkdirs();
                }
                file.transferTo(savafile);//上传文件
            }
            //获取服务老师
            CoreUser user = getLoginUser(request);
            int userid = user.getId().intValue();
            String getTeacherNameSql = "SELECT b.* FROM  \n" +
                    "`customer_user_map`  a \n" +
                    " INNER JOIN `customer_info` b ON a.`customer_id` = b.`customer_id` AND b.`is_teacher`=1 \n" +
                    " WHERE a.user_id="+userid+"";
            List<BaseEntity> list = sqlManager.execute(new SQLReady(getTeacherNameSql),BaseEntity.class);

            String TeacherName="";
            if(list.size()==0){
                TeacherName="异常 userid="+String.valueOf(userid);
            }else{
                TeacherName  = list.get(0).get("customerName").toString();
            }

            //获取当前时间
            Date nowdate = new EDateUtil().getNowDate();
            //获取文件网络地址
            String internetFilePaht = savafile.getPath().replace("/opt/static","http://static.51sdx.com/images");


            //判断是插入数据还是更新数据
            List<ContractServiceRecord> oldContractservicerecore = sqlManager.query(ContractServiceRecord.class).andEq("contract_id",contractid)
                    .andEq("type_id",srviceid).andEq("node_id",nodeid).select();

            if (oldContractservicerecore.size()>0){
                //更新数据
                if (oldContractservicerecore.size()!=1){
                    object.put("msg","异常");
                    return object;
                }
                ContractServiceRecord newContractservicerecore =  oldContractservicerecore.get(0);
                newContractservicerecore.setContent(context);
                if(savafile==null || "null".equals(savafile)){

                }else {
                    newContractservicerecore.setFiles(newContractservicerecore.getFiles()+";"+internetFilePaht);
                }
                newContractservicerecore.setUpdateTime(nowdate);
                newContractservicerecore.setNodeSchedule(1);
                sqlManager.updateById(newContractservicerecore);

            }else{
                //获取sort
                String sort = sqlManager.execute(new SQLReady("SELECT sort FROM `contract_service_node_map` WHERE service_id = ? AND node_id= ? ",
                        srviceid,nodeid),BaseEntity.class).get(0).get("sort").toString();
                System.out.println("sort = "+sort);

                //插入数据
                ContractServiceRecord contractServiceRecord = new ContractServiceRecord();
                contractServiceRecord.setContractId(Integer.valueOf(contractid));
                contractServiceRecord.setTypeId(Integer.valueOf(srviceid));
                contractServiceRecord.setNodeSchedule(1);
                contractServiceRecord.setSort(Integer.valueOf(sort));
                contractServiceRecord.setNodeId(Integer.valueOf(nodeid));
                contractServiceRecord.setContent(context);
                if(savafile==null || "null".equals(savafile)){
                    contractServiceRecord.setFiles("");
                }else {
                    contractServiceRecord.setFiles(internetFilePaht);
                }

                if(!"null".equals(TeacherName) && TeacherName!=null){
                    contractServiceRecord.setTeacher(TeacherName);
                }
                contractServiceRecord.setRecordTime(nowdate);
                contractServiceRecord.setCreateTime(nowdate);
                contractServiceRecord.setUpdateTime(nowdate);
                sqlManager.insertTemplate(contractServiceRecord);
            }

            object.put("msg","成功");
        } catch (IOException e) {
            e.printStackTrace();
            object.put("msg","文件上传失败");
        }
        return object;
    }








    public JSONArray listEntityToJson(List<BaseEntity> list){
        JSONArray arr = new JSONArray();
        for (int i=0 ;i<list.size();i++){
            arr.add(singleEntityToJson(list.get(i)) );
        }
        return arr;
    }
    public JSONObject singleEntityToJson(BaseEntity single) {
        JSONObject ResultJson = new JSONObject();
        Map<String,Object> map = single.getTails();
        for (Map.Entry<String,Object> entry : map.entrySet()){
            Object value = entry.getValue();
            if (value==null || value == "null"){
                value="";
            }
            ResultJson.put(entry.getKey(),value);
        }
        return ResultJson;
    }



}
